/*
 * TestFul - http://code.google.com/p/testful/
 * Copyright (C) 2012 Matteo Miraz
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package testful.evolutionary;

import java.util.IdentityHashMap;
import java.util.Iterator;
import java.util.Map;

import jmetal.util.PseudoRandom;
import testful.model.Operation;
import testful.model.ReferenceFactory;
import testful.model.TestCluster;
import ec.util.MersenneTwisterFast;

/**
 * TODO describe me!
 * 
 * @author Administrator
 */
public class SwapOperation {

	private IdentityHashMap<String, Operation> swapOperators = new IdentityHashMap<String, Operation>();
	private final float probRemove = 0.66f;
	private TestfulProblem problem;
	private Operation[] ops;

	public SwapOperation(TestfulProblem problem, Operation[] ops) {
		this.problem = problem;
		this.ops = ops;
		intialSwap();
	}

	public SwapOperation() {
	}

	private void intialSwap() {
		MersenneTwisterFast random = PseudoRandom.getMersenneTwisterFast();
		TestCluster cluster = problem.getCluster();
		ReferenceFactory refFactory = problem.getReferenceFactory();

		int len = random.nextInt(5);
		while (len >= 0) {

			String key = (!random.nextBoolean(probRemove)) ? new String("ADD")
			: new String("REMOVE");
			Operation op;
			if (key.equals("ADD")) {
				op = Operation.randomlyGenerate(cluster, refFactory, random);
			} else {
				op = ops[random.nextInt(ops.length)];
			}
			swapOperators.put(key, op);
			len--;
		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see java.lang.Object#toString()
	 */
	@Override
	public String toString() {
		StringBuffer sb = new StringBuffer("\n**** intial swap **** "
				+ swapOperators.size() + "\n");
		Iterator iter = swapOperators.entrySet().iterator();
		while (iter.hasNext()) {
			Map.Entry entry = (Map.Entry) iter.next();
			String key = (String) entry.getKey();
			Operation op = (Operation) entry.getValue();
			sb.append("*** " + key + " " + op.toString() + "\n");
		}

		return sb.toString();
	}

	/**
	 * @return the swapOperators
	 */
	public IdentityHashMap<String, Operation> getSwapOperators() {
		return swapOperators;
	}

	/**
	 * @param swapOperators the swapOperators to set
	 */
	public void setSwapOperators(IdentityHashMap<String, Operation> swapOperators) {
		this.swapOperators = swapOperators;
	}



}
